package com.itc.bi.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.itc.bi.config.MinioAPI;
import com.itc.bi.dto.MqttClientDto;
import com.itc.bi.entity.MqMqttClientEntity;
import com.itc.bi.service.MqMqttClientService;
import com.itc.common.core.domain.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @program: itc-airport-cloud
 * @description: mqtt相关接口
 * @author: songxiude
 * @create: 2024-07-15 14:47
 **/
@RestController
@Api(value = "mqtt接口", tags = "mqtt接口")
@RequestMapping("/mqtt")
public class MqttController {
    @Autowired
    private MqMqttClientService mqttClientService;

    @Autowired
    private MinioAPI minioAPI;

    @Autowired
    private ThreadPoolExecutor executor;

    @GetMapping("/thread")
    public R thread() {

        Map map =new HashMap();
        long taskCount = executor.getTaskCount();
        long completedTaskCount = executor.getCompletedTaskCount();
        int activeCount = executor.getActiveCount();
        int size = executor.getQueue().size();
        map.put("提交任务数-->",taskCount);
        map.put("完成任务数-->",completedTaskCount);
        map.put("当前有多少线程正在处理任务-->",activeCount);
        map.put("还剩多少个任务未执行-->",size);
        map.put("当前可用队列长度-->",executor.getQueue().remainingCapacity());
        return R.ok(map);
    }

    @PostMapping("/mqttSave")
    @ApiOperation(value = "添加mqtt链接")
    public R mqttSave(@RequestBody MqMqttClientEntity mqMqttClient) {
        if (mqttClientService.mqttSave(mqMqttClient)) {
            return R.ok();
        }
        return R.fail("创建mqtt链接失败");
    }

    @PostMapping("/mqttUpdate")
    @ApiOperation(value = "修改mqtt链接")
    @ApiOperationSupport(order = 2, includeParameters = {
            "mqMqttClient.mqttName",
            "mqMqttClient.serverHost",
            "mqMqttClient.serverPort",
            "mqMqttClient.clientType",
            "mqMqttClient.username",
            "mqMqttClient.password",
            "mqMqttClient.caFile",
            "mqMqttClient.ccFile",
            "mqMqttClient.ckFile",
            "mqMqttClient.clientTopic",
            "mqMqttClient.clientCleanSession",
            "mqMqttClient.enableFlag",
            "mqMqttClient.remark"
    })
    public R mqttUpdate(@RequestBody MqMqttClientEntity mqMqttClient) {
        if (mqttClientService.mqttUpdate(mqMqttClient)) {
            return R.ok();
        }
        return R.fail("修改失败");
    }

    @PostMapping("/mqttList")
    @ApiOperation(value = "获取mqtt链接列表")
    @ApiOperationSupport(order = 3, includeParameters = {
            "mqttClientDto.mqttName",
            "mqttClientDto.page",
            "mqttClientDto.size"
    })
    public R mqttList(@RequestBody MqttClientDto mqttClientDto) {
        IPage<MqMqttClientEntity> list = mqttClientService.mqttList(mqttClientDto);
        return R.ok(list, "获取链接列表成功");
    }

    @PostMapping("/startMqtt")
    @ApiOperation(value = "手动启动mqtt")
    public R startMqtt(@RequestParam("id") Long id) {
        if (mqttClientService.startMqtt(id)) {
            return R.ok();
        }
        return R.fail("启动失败了");
    }

    @PostMapping("/removeMqtt")
    @ApiOperation(value = "删除mqtt链接")
    public R removeMqtt(@RequestParam("client_id") String clientId) {
        if (mqttClientService.removeMqtt(clientId)) {
            return R.ok();
        }
        return R.fail("删除mqtt链接失败");
    }


    @PostMapping("/upload")
    @ApiOperation(value = "证书文件上传", notes = "证书文件上传")
    @ApiOperationSupport(order = 5)
    public R uploadClient(@ApiParam(name = "file", value = "证书文件", required = true) MultipartFile file) {
        try {
            //规定日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            //获取上传时的当前时间
            LocalDateTime now = LocalDateTime.now();
            //将当前时间按照规定格式转换
            String format = now.format(formatter);
            // 获取源文件名
            String orgName = file.getOriginalFilename();
            // 获取后缀
            String suffix = orgName.substring(orgName.lastIndexOf("."));
            //给要上传的文件起名字
            String fileName = format + "/" + System.currentTimeMillis() + suffix;
            //将文件上传到minio中存储，并将文件路径返回
            minioAPI.uploadInputStream(minioAPI.getBUCKET(), fileName, file.getInputStream(), file.getContentType());
            return R.ok(fileName);
        } catch (Exception e) {
            return R.fail("客户端上传失败");
        }
    }
}